package com.cyl.manager.aws.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.aws.convert.ShopStatistics2Convert;
import com.cyl.manager.aws.convert.ShopStatisticsConvert;
import com.cyl.manager.aws.domain.entity.ShopStatistics;
import com.cyl.manager.aws.pojo.query.ShopStatisticsQuery;
import com.cyl.manager.aws.pojo.vo.ShopStatisticsSqlVO;
import com.cyl.manager.aws.pojo.vo.ShopStatisticsVO;
import com.cyl.manager.aws.service.ShopStatisticsService;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
/**
 * 店铺数据统计Controller
 *
 * @author zcc
 * @date 2025-03-06
 */
@Slf4j
@Api(description ="店铺数据统计接口列表")
@RestController
@RequestMapping("/aws/shopStatistics")
public class ShopStatisticsController extends BaseController {
    @Autowired
    private ShopStatisticsService service;
    @Autowired
    private ShopStatisticsConvert convert;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private MemberMapper memberMapper;
    
    @ApiOperation("查询店铺数据统计列表")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:list')")
    @PostMapping("/list")
    public ResponseEntity<Page<ShopStatistics>> list(@RequestBody ShopStatisticsQuery query, Pageable page) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
        }
    	Long qxDeptId = SecurityUtils.getQxDeptIdId();
    	if(qxDeptId!=null) {
    		query.setQxDeptId(qxDeptId);
    	}
        List<ShopStatistics> list = service.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
    
    
    @ApiOperation("查询店铺数据统计最新更新时间")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:list')")
    @GetMapping("/selectMaxCreateTime")
    public ResponseEntity<String> selectMaxCreateTime() {
        return ResponseEntity.ok(service.selectMaxCreateTime());
    }
    
    
    
    @ApiOperation("查询店铺数据统计今日")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:list')")
    @PostMapping("/selectToDay")
    public ResponseEntity<ShopStatistics> selectToDay(String date) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId==null) {
        	return ResponseEntity.ok(null);
        }
		ShopStatistics shopStatistics = service.selectShopToDayByDeptZbjId(qrDeptZbjId,date);
		return ResponseEntity.ok(shopStatistics);
    }
    
   
    @ApiOperation("查询店铺数据统计列表")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:list')")
    @PostMapping("/listTj")
    public ResponseEntity<ShopStatistics> listTj(@RequestBody ShopStatisticsQuery query) {
    	  Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
    	 query.setSfDate("false");
     	 query.setType("1");
     	 query.setType("1");
     	 query.setByDesc(null);
     	 query.setByColumn(null);
    
        if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
        }
      	Long qxDeptId = SecurityUtils.getQxDeptIdId();
    	if(qxDeptId!=null) {
    		query.setQxDeptId(qxDeptId);
    	}
    	
    	
       
          boolean boolDay = false;
          Integer[] tjdataRange = query.getTjdataRange();
          if (tjdataRange != null && tjdataRange.length == 2) {
              Integer start = tjdataRange[0];
              Integer end = tjdataRange[1];
              Integer dayTime = Integer.parseInt(DateUtil.format(DateUtil.date(), "yyyyMMdd"));
              if(end.intValue() == dayTime.intValue()) {//是今天
                  LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
                  end = Integer.parseInt(DateUtil.format(endTime, "yyyyMMdd"));
                  boolDay = true;
              }
              query.setTjdataRange(new Integer[] {start,end});
          }else {
        	   boolDay = true;
          }
          
        List<ShopStatistics> list = service.selectList(query, null);
        ShopStatistics dbData =  null;
        if(list!=null && list.size()>0) {
        	 for (ShopStatistics shopStatistics : list) { //多直播间循环加
        		 dbData =  ShopStatistics2Convert.dosAdddos(shopStatistics, dbData);
			 }
        }
         
        if(boolDay && qxDeptId==null) {
	        ShopStatistics shopStatistics =  service.selectShopToDayByDeptZbjId(qrDeptZbjId,null);
	        ShopStatistics dayData =  ShopStatistics2Convert.dosAdddos(shopStatistics, dbData);
	        
	        DateTime strTime =  DateUtil.parse(tjdataRange[0]+"000000");
			DateTime endTime =  DateUtil.parse(tjdataRange[1]+"235959");
			QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
			queryWrapper.between("spread_time", strTime, endTime);
			if(qrDeptZbjId!=null) {
				queryWrapper.eq("dept_zbj_id", qrDeptZbjId);
	        }
			dayData.setMemberDayConut(memberMapper.selectCount(queryWrapper));
			
	        return ResponseEntity.ok(dayData);
        }
        try {
        	DateTime strTime =  DateUtil.parse(tjdataRange[0]+"000000");
			DateTime endTime =  DateUtil.parse(tjdataRange[1]+"235959");
			QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
			queryWrapper.between("spread_time", strTime, endTime);
			if(qrDeptZbjId!=null) {
				queryWrapper.eq("dept_zbj_id", qrDeptZbjId);
	        }
			
			dbData.setMemberDayConut(memberMapper.selectCount(queryWrapper));
		} catch (Exception e) {
		    
		}
        return ResponseEntity.ok(dbData);
    }
    
    
    @ApiOperation("查询店铺数据统计列表")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:list')")
    @PostMapping("/listAll")
    public ResponseEntity<List<ShopStatistics>> listAll(@RequestBody ShopStatisticsQuery query) {
    	  Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
          if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
          }
      	Long qxDeptId = SecurityUtils.getQxDeptIdId();
    	if(qxDeptId!=null) {
    		query.setQxDeptId(qxDeptId);
    	}
          boolean boolDay = false;
          Integer[] tjdataRange = query.getTjdataRange();
          if (tjdataRange != null && tjdataRange.length == 2) {
              Integer start = tjdataRange[0];
              Integer end = tjdataRange[1];
              Integer dayTime = Integer.parseInt(DateUtil.format(DateUtil.date(), "yyyyMMdd"));
              if(end.intValue() == dayTime.intValue()) {//是今天
                  LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
                  end = Integer.parseInt(DateUtil.format(endTime, "yyyyMMdd"));
                  boolDay = true;
              }
              query.setTjdataRange(new Integer[] {start,end});
          }else {
        	   boolDay = true;
          }
          
        List<ShopStatistics> list = service.selectList(query, null);
        if(boolDay && qxDeptId==null) {
                list.add(service.selectShopToDayByDeptZbjId(qrDeptZbjId,null));
        }
        return ResponseEntity.ok(list);
    }
    
    @ApiOperation("导出店铺数据统计列表")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:export')")
    @Log(title = "店铺数据统计", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public ResponseEntity<String> export(ShopStatisticsQuery query) {
    	  Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
          if(qrDeptZbjId!=null) {
          	query.setDeptZbjId(qrDeptZbjId);
          }
      	Long qxDeptId = SecurityUtils.getQxDeptIdId();
    	if(qxDeptId!=null) {
    		query.setQxDeptId(qxDeptId);
    	}
        List<ShopStatistics> list = service.selectList(query, null);
        ExcelUtil<ShopStatisticsVO> util = new ExcelUtil<>(ShopStatisticsVO.class);
        List<ShopStatisticsVO>  retList = convert.dos2vos(list);
        if(retList!=null) {
        	for (ShopStatisticsVO shopStatisticsVO : retList) {
        		Long deptId = shopStatisticsVO.getDeptDpId();
        		if(deptId!=null) {
        			SysDept sysDept = deptService.getCacheSysDept(deptId);
        			if(sysDept!=null) {
                		shopStatisticsVO.setDeptDpName(sysDept.getDeptName());
                		shopStatisticsVO.setDeptDpDz(sysDept.getProvince()+"-"+sysDept.getCity()+"-"+sysDept.getDistrict()+"-"+sysDept.getAddress());
        			}
        		}
			}
        }
        return ResponseEntity.ok(util.writeExcel(retList, "店铺数据统计数据"));
    }

    @ApiOperation("获取店铺数据统计详细信息")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:query')")
    @GetMapping(value = "/{id}")
    public ResponseEntity<ShopStatistics> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }
    
     
    
    @ApiOperation("获取店铺数据统计详细信息更新")
    @GetMapping(value = "/insertShopDay")
    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:insertday')")
    public ResponseEntity<String> insertShopDay(String date) {
    	String ok = "操作成功！";
    	LocalDate thisLocalDate = LocalDate.now();
    	if(date!=null) {
    		thisLocalDate = LocalDate.parse(date);
    	}
        LocalDateTime strTime = LocalDateTime.of(thisLocalDate, LocalTime.MIN);
    	LocalDateTime endTime = LocalDateTime.of(thisLocalDate, LocalTime.MAX);
    	String redisKey = "admin_statistics_shop_123456";
        String redisValue = redisKey+"_"+strTime.toString();
        	try{    
    		    redisService.lock(redisKey,redisValue,60*30);
    		    service.insertShopDay(strTime, endTime);
        	}catch (Exception e){
        		 log.error("insertShopDay",e);
        		 ok = "1: "+e.getMessage();
        	}finally {
    	        try {
                redisService.unLock(redisKey,redisValue);
            }catch (Exception e){
	            log.error("insertShopDay",e);
       		    ok = "2: "+e.getMessage();

            }
        }
		return ResponseEntity.ok(ok);
    }
    public  ShopStatisticsSqlVO getShopStatisticsSql(LocalDateTime strTime,LocalDateTime endTime) {
    	int tjdata = Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd"));
 		int	tjyear = Integer.parseInt(DateUtil.format(strTime, "yyyy"));
 		int	tjmonth = Integer.parseInt(DateUtil.format(strTime, "MM"));
 		int	tjweek = Integer.parseInt(DateUtil.format(strTime, "w"));
 		int	tjday = Integer.parseInt(DateUtil.format(strTime, "dd"));
 		ShopStatisticsSqlVO shopStatisticsSqlVO = new ShopStatisticsSqlVO();
    	shopStatisticsSqlVO.setCreateTime(LocalDateTime.now());
    	shopStatisticsSqlVO.setStrTime(strTime);
    	shopStatisticsSqlVO.setEndTime(endTime);
    	shopStatisticsSqlVO.setTjdata(tjdata);
    	shopStatisticsSqlVO.setTjyear(tjyear);
    	shopStatisticsSqlVO.setTjmonth(tjmonth);
    	shopStatisticsSqlVO.setTjweek(tjweek);
    	shopStatisticsSqlVO.setTjday(tjday);
    	return shopStatisticsSqlVO;
	}
    
    
//    
//
//    @ApiOperation("新增店铺数据统计")
//    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:add')")
//    @Log(title = "店铺数据统计", businessType = BusinessType.INSERT)
//    @PostMapping
//    public ResponseEntity<Integer> add(@RequestBody ShopStatistics shopStatistics) {
//        return ResponseEntity.ok(service.insert(shopStatistics));
//    }
//
//    @ApiOperation("修改店铺数据统计")
//    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:edit')")
//    @Log(title = "店铺数据统计", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public ResponseEntity<Integer> edit(@RequestBody ShopStatistics shopStatistics) {
//        return ResponseEntity.ok(service.update(shopStatistics));
//    }
//
//    @ApiOperation("删除店铺数据统计")
//    @PreAuthorize("@ss.hasPermi('aws:shopStatistics:remove')")
//    @Log(title = "店铺数据统计", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public ResponseEntity<Integer> remove(@PathVariable Long[] ids) {
//        return ResponseEntity.ok(service.deleteByIds(ids));
//    }
}
